import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:studymanage/core/global.dart';
import 'package:studymanage/course/course_detail.dart';
import 'package:studymanage/util/request.dart';

class CourseIntro extends StatefulWidget {
   Map<String,dynamic> courseIntro;
   final String courseId;
   final String courseSectionId;
   final update;

   CourseIntro(this.courseIntro,this.courseId,this.courseSectionId,this.update);

   @override
  State<StatefulWidget> createState() {
    return CourseIntroState();
  }
}

class CourseIntroState extends State<CourseIntro> {
  Map<String,dynamic> _courseIntro ={
    "longCoverUrl":""
  };
  // 当前第几周
  int _currentTab = 0;

  // 文本收起、展开参数
  bool _isShowMore = false; // 是否展开
  int _maxLines = 3; // 文本最大行数

  @override
  void initState() {
    setState(() {
      _courseIntro = widget.courseIntro;
    });
    if(widget.courseSectionId != null){
      for(int i=0;i<_courseIntro["courseSectionList"].length ;i++){
        if(_courseIntro["courseSectionList"][i]["id"] == widget.courseSectionId){
          setState(() {
            _currentTab = i;
          });
        }
      }
    }
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        brightness: Brightness.light,
        title: Text(
          '课程介绍',
          style: TextStyle(
            fontFamily: 'PingFangSC-Medium',
            fontSize: ScreenUtil().setSp(16),
            fontWeight: FontWeight.w600,
            color: Color.fromRGBO(51, 51, 51, 1),
            height: 1,
          ),
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: Icon(
            Icons.navigate_before,
            color: Color.fromRGBO(51, 51, 51, 1),
            size: ScreenUtil().setSp(30),
          ),
          onPressed: () {
            if(widget.update!=null){
              widget.update();
            }
            Navigator.pop(context);
          },
        ),
      ),
      body: RefreshIndicator(
        onRefresh: ()=>_refresh(),
        child: SingleChildScrollView(
          physics: AlwaysScrollableScrollPhysics(),
          child: Column(
            children: <Widget>[
              Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.width*0.4,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: NetworkImage(_courseIntro['longCoverUrl']),
                    fit: BoxFit.fill,
                  ),
                ),
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      bottom: 0,
                      child: Offstage(
                        offstage: _courseIntro['className']==null,
                        child: Container(
                          width: ScreenUtil().setWidth(248),
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage('assets/images/course/class_bg.png'),
                              fit: BoxFit.fitHeight,
                            ),
                          ),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Container(
                                width: ScreenUtil().setWidth(218),
                                margin: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(30),
                                ),
                                child: Text(
                                  _courseIntro['className'],
                                  style: TextStyle(
                                    fontFamily: 'PingFangSC-Medium',
                                    fontSize: ScreenUtil().setSp(14),
                                    fontWeight: FontWeight.w600,
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Center(
                child: _courseIntro['courseSectionList'].length>0 ?  Column(
                  children: <Widget>[
                    Container(
                      width: MediaQuery.of(context).size.width,
                      height: ScreenUtil().setHeight(78),
                      margin: EdgeInsets.only(
                        top: ScreenUtil().setHeight(13.5),
                      ),
                      child: ListView.builder(
                        scrollDirection: Axis.horizontal,
                        itemCount: _courseIntro['courseSectionList'].length,
                        itemBuilder: (context, index) {
                          return GestureDetector(
                            child: Container(
                              width: ScreenUtil().setWidth(137),
                              height: ScreenUtil().setHeight(78),
                              margin: EdgeInsets.only(
                                left: index == 0 ? ScreenUtil().setWidth(12) : ScreenUtil().setWidth(10),
                                right: index == _courseIntro['courseSectionList'].length - 1 ? ScreenUtil().setWidth(12) : 0,
                              ),
                              padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(14.5),
                                right: ScreenUtil().setWidth(14.5),
                                top: ScreenUtil().setHeight(10),
                                bottom: ScreenUtil().setHeight(22),
                              ),
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  image: index == _currentTab ? AssetImage('assets/images/course/schedule_current.png') : AssetImage('assets/images/course/schedule.png'),
                                  fit: BoxFit.fill,
                                ),
                              ),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Text(_courseIntro['courseSectionList'][index]['courseSectionBigTitle'],
                                    style: TextStyle(
                                      fontFamily: 'PingFangSC-Medium',
                                      fontSize: ScreenUtil().setHeight(14),
                                      fontWeight: FontWeight.w600,
                                      color: index == _currentTab ? Colors.white : Color.fromRGBO(51, 51, 51, 1),
                                    ),
                                  ),
                                  Text(_courseIntro['courseSectionList'][index]['courseSectionSmallTitle'],
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      fontFamily: 'PingFangSC-Light',
                                      fontSize: 12,
                                      fontWeight: FontWeight.w300,
                                      color: index == _currentTab ? Colors.white : Color.fromRGBO(51, 51, 51, 1),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            onTap: () {
                                setState(() {
                                  _currentTab = index;
                                });
                            },
                          );
                        },
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.only(
                        left: ScreenUtil().setWidth(12),
                        right: ScreenUtil().setWidth(12),
                        top: ScreenUtil().setHeight(20.5),
                      ),
                      child: Column(
                        children: <Widget>[
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                             Expanded(
                               child:  Row(
                                 children: <Widget>[
                                   Text(
                                     _courseIntro['courseSectionList'][_currentTab]['courseSectionBigTitle'],
                                     style: TextStyle(
                                       fontFamily: 'PingFangSC-Medium',
                                       fontSize: ScreenUtil().setSp(15),
                                       fontWeight: FontWeight.w600,
                                       color: Color.fromRGBO(51, 51, 51, 1),
                                     ),
                                   ),
                                   Expanded(
                                     child: Container(
                                       margin: EdgeInsets.only(
                                       ),
                                       child: Text(
                                         _courseIntro['courseSectionList'][_currentTab]['courseSectionSmallTitle'],
                                         maxLines: 1,
                                         overflow: TextOverflow.ellipsis,
                                         style: TextStyle(
                                           fontFamily: 'PingFangSC-Medium',
                                           fontSize: ScreenUtil().setSp(15),
                                           fontWeight: FontWeight.w600,
                                           color: Color.fromRGBO(51, 51, 51, 1),
                                         ),
                                       ),
                                     ),
                                   ),
                                 ],
                               ),
                             ),
                              GestureDetector(
                                child: Row(
                                  children: <Widget>[
                                    Container(
                                      margin: EdgeInsets.only(
                                        right: ScreenUtil().setWidth(6),
                                      ),
                                      child: Text(
                                        _isShowMore ? '收起' : '详情',
                                        style: TextStyle(
                                          fontFamily: 'PingFangSC-Regular',
                                          fontSize: ScreenUtil().setSp(12),
                                          color: Color.fromRGBO(210, 180, 142, 1),
                                        ),
                                      ),
                                    ),
                                    Icon(
                                      _isShowMore ? Icons.arrow_drop_up : Icons.arrow_drop_down,
                                      color: Color.fromRGBO(210, 180, 142, 1),
                                    ),
                                  ],
                                ),
                                onTap: () {
                                  setState(() {
                                    _isShowMore = !_isShowMore;
                                  });
                                  print(_isShowMore);
                                },
                              ),
                            ],
                          ),
                          _richText(_courseIntro['courseSectionList'][_currentTab]['courseSectionIntro']),
                        ],
                      ),
                    ),
                    Offstage(
                      offstage: Global.profile.userTypeEnum ==2,
                      child: Container(
                        padding: EdgeInsets.only(
                          left: ScreenUtil().setWidth(12),
                          right: ScreenUtil().setWidth(12),
                          top: ScreenUtil().setHeight(25.5),
                          bottom: ScreenUtil().setHeight(20.5),
                        ),
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(
                              width: ScreenUtil().setHeight(7.5),
                              color: Color.fromRGBO(248, 248, 248, 1),
                            ),
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              '已学' + ((_courseIntro['courseSectionList'][_currentTab]['courseSectionProgress']*100).round()).toString() + '%',
                              style: TextStyle(
                                fontFamily: 'PingFangSC-Regular',
                                fontSize: ScreenUtil().setSp(11),
                                color: Color.fromRGBO(210, 180, 142, 1),
                              ),
                            ),
                            SizedBox(
                              width: ScreenUtil().setWidth(287),
                              height: ScreenUtil().setHeight(4),
                              child: LinearProgressIndicator(
                                // 0~1的浮点数，用来表示进度多少;如果 value 为 null 或空，则显示一个动画，否则显示一个定值
                                value: double.parse(_courseIntro['courseSectionList'][_currentTab]['courseSectionProgress'].toString()),
                                backgroundColor: Color.fromRGBO(249, 239, 228, 1),
                                valueColor: AlwaysStoppedAnimation<Color>(Color.fromRGBO(210, 180, 142, 1)),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Container(
                      width: MediaQuery.of(context).size.width,
                      padding: EdgeInsets.only(
                        left: ScreenUtil().setWidth(13.5),
                        right: ScreenUtil().setWidth(13.5),
                        bottom: ScreenUtil().setHeight(18),
                      ),
                      child: ListView.builder(
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                        itemCount: _courseIntro['courseSectionList'][_currentTab]['taskList'].length,
                        itemBuilder: (context, index) {
                          return GestureDetector(
                            child: Container(
                              padding: EdgeInsets.only(
                                top: ScreenUtil().setHeight(18),
                                bottom: ScreenUtil().setHeight(18),
                              ),
                              decoration: BoxDecoration(
                                border: Border(
                                  bottom: BorderSide(
                                    width: ScreenUtil().setHeight(0.5),
                                    color: Color.fromRGBO(238, 238, 238, 1),
                                  ),
                                ),
                              ),
                              width: MediaQuery.of(context).size.width,
                              child: Column(
                                children: <Widget>[
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: <Widget>[
                                      Expanded(
                                        child: Row(
                                          children: <Widget>[
                                            Container(
                                              width: 30,
                                              child: Text(
                                                (index + 1).toString().length == 2 ? (index + 1).toString() : '0' + (index + 1).toString(),
                                                style: TextStyle(
                                                  fontFamily: 'PingFangSC-Regular',
                                                  fontSize: ScreenUtil().setSp(14),
                                                  fontStyle: FontStyle.italic,
                                                  color: false ? Color.fromRGBO(153, 153, 153, 1) : Color.fromRGBO(51, 51, 51, 1),
                                                ),
                                              ),
                                            ),
                                            Text(
                                              _courseIntro['courseSectionList'][_currentTab]['taskList'][index]['taskTitle'],
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              softWrap: true,
                                              style: TextStyle(
                                                fontFamily: 'PingFangSC-Regular',
                                                fontSize: ScreenUtil().setSp(14),
                                                color: _courseIntro['courseSectionList'][_currentTab]['taskList'][index]['boolShareEnum']==1
                                                    &&  _courseIntro['courseSectionList'][_currentTab]['taskList'][index]['boolPunchClockEnum']==1
                                                    && _courseIntro['courseSectionList'][_currentTab]['taskList'][index]['boolCommentEnum']==1
                                                    ? Color.fromRGBO(153, 153, 153, 1) : Color.fromRGBO(51, 51, 51, 1),
                                              ),
                                            ),

                                          ],
                                        ),
                                      ),
                                      Container(
                                        height: ScreenUtil().setHeight(21.5),
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: <Widget>[
                                            Icon(
                                              Icons.navigate_next,
                                              color: Color.fromRGBO(133, 133, 133, 1),
                                              size: ScreenUtil().setSp(20),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: <Widget>[
                                      Container(width: 30,),
                                      Offstage(
                                        offstage: _courseIntro['courseSectionList'][_currentTab]['taskList'][index]['boolPunchClockEnum']==2,
                                        child: Container(
                                          width: ScreenUtil().setWidth(50),
                                          height: ScreenUtil().setHeight(20),
                                          margin: EdgeInsets.only(
                                            top: ScreenUtil().setHeight(5),
                                          ),
                                          decoration: BoxDecoration(
                                            color: Color.fromRGBO(246, 246, 246, 1),
                                            borderRadius: BorderRadius.all(
                                              Radius.circular(ScreenUtil().setHeight(15)),
                                            ),
                                          ),
                                          child: Center(
                                            child: Text('已打卡',
                                              style: TextStyle(
                                                fontFamily: 'PingFangSC-Light',
                                                fontSize: ScreenUtil().setSp(11),
                                                fontWeight: FontWeight.w300,
                                                color: Color.fromRGBO(153, 153, 153, 1),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                      Offstage(
                                        offstage:  _courseIntro['courseSectionList'][_currentTab]['taskList'][index]['boolShareEnum']==2,
                                        child: Container(
                                          width: ScreenUtil().setWidth(50),
                                          height: ScreenUtil().setHeight(20),
                                          margin: EdgeInsets.only(
                                            top: ScreenUtil().setHeight(5),
                                            left: ScreenUtil().setWidth(5),
                                          ),
                                          decoration: BoxDecoration(
                                            color: Color.fromRGBO(246, 246, 246, 1),
                                            borderRadius: BorderRadius.all(
                                              Radius.circular(ScreenUtil().setHeight(15)),
                                            ),
                                          ),
                                          child: Center(
                                            child: Text('已分享',
                                              style: TextStyle(
                                                fontFamily: 'PingFangSC-Light',
                                                fontSize: ScreenUtil().setSp(11),
                                                fontWeight: FontWeight.w300,
                                                color: Color.fromRGBO(153, 153, 153, 1),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                      Offstage(
                                        offstage: _courseIntro['courseSectionList'][_currentTab]['taskList'][index]['boolCommentEnum']==2,
                                        child: Container(
                                          width: ScreenUtil().setWidth(50),
                                          height: ScreenUtil().setHeight(20),
                                          margin: EdgeInsets.only(
                                            top: ScreenUtil().setHeight(5),
                                            left: ScreenUtil().setWidth(5),
                                          ),
                                          decoration: BoxDecoration(
                                            color: Color.fromRGBO(246, 246, 246, 1),
                                            borderRadius: BorderRadius.all(
                                              Radius.circular(ScreenUtil().setHeight(15)),
                                            ),
                                          ),
                                          child: Center(
                                            child: Text('已点评',
                                              style: TextStyle(
                                                fontFamily: 'PingFangSC-Light',
                                                fontSize: ScreenUtil().setSp(11),
                                                fontWeight: FontWeight.w300,
                                                color: Color.fromRGBO(153, 153, 153, 1),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                            onTap: () {
                              Request().post<Map<String,dynamic>>("/multiapi/c191v_task",
                                  data: {"id": _courseIntro['courseSectionList'][_currentTab]['taskList'][index]['id'],
                                    "courseSectionId":_courseIntro['courseSectionList'][_currentTab]['taskList'][index]['courseSectionId']}).then((response){
                                Navigator.push(context, MaterialPageRoute(builder: (context) => CourseDetail(response.data,widget.courseId,(id,boolShareEnum,boolPunchClockEnum)=>_updateCourse(id, boolShareEnum,boolPunchClockEnum))));
                              });
                            },
                          );
                        },
                      ),
                    ),
                  ],
                ) : Text("暂无数据"),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 展开、收起文本
  Widget _richText(String _text) {
    if (_isOverMaxLines(_text)) { // text 是否超出 maxLines
      if (_isShowAllText()) { // 展开
        return Container(
          alignment: Alignment.centerLeft,
          margin: EdgeInsets.only(
            top: ScreenUtil().setHeight(18.5),
          ),
          child: Text(
            _text,
            style: TextStyle(
              fontFamily: 'PingFangSC-Light',
              fontSize: ScreenUtil().setSp(13),
              fontWeight: FontWeight.w300,
              color: Color.fromRGBO(133, 133, 133, 1),
              height: 1.5,
            ),
            textAlign: TextAlign.justify,
          ),
        );
      } else {
        return Container(
          alignment: Alignment.centerLeft,
          margin: EdgeInsets.only(
            top: ScreenUtil().setHeight(18.5),
          ),
          child: Text(
            _text,
            maxLines: _maxLines,
            style: TextStyle(
              fontFamily: 'PingFangSC-Light',
              fontSize: ScreenUtil().setSp(13),
              fontWeight: FontWeight.w300,
              color: Color.fromRGBO(133, 133, 133, 1),
              height: 1.5,
            ),
            textAlign: TextAlign.justify,
            overflow: TextOverflow.ellipsis,
          ),
        );
      }
    } else { // text 没有超出 maxLines
      return Container(
        alignment: Alignment.centerLeft,
        margin: EdgeInsets.only(
          top: ScreenUtil().setHeight(18.5),
        ),
        child: Text(
          _text,
          style: TextStyle(
            fontFamily: 'PingFangSC-Light',
            fontSize: ScreenUtil().setSp(13),
            fontWeight: FontWeight.w300,
            color: Color.fromRGBO(133, 133, 133, 1),
            height: 1.5,
          ),
          textAlign: TextAlign.justify,
          overflow: TextOverflow.ellipsis,
        ),
      );
    }
  }

  // 判断 text 是否超出 maxLines
  bool _isOverMaxLines(String _text) {
    TextPainter _textPainter = TextPainter(
      maxLines: _maxLines,
      text: TextSpan(
        text: _text,
      ),
      textDirection: TextDirection.ltr,
    )..layout(
        maxWidth: MediaQuery.of(context).size.width - ScreenUtil().setWidth(62),
        minWidth:
        MediaQuery.of(context).size.width / 2 - ScreenUtil().setWidth(31));

    if (_textPainter.didExceedMaxLines) {
      // 判断是否超出 maxLines, 即是否需要隐藏
      return true;
    } else {
      return false;
    }
  }

  // 是否点击 Show More 按钮，即是否展示全部 text
  bool _isShowAllText() {
    if (_isShowMore) {
      return true;
    } else {
      return false;
    }
  }
  Future<Null> _refresh()async{
    Request().post<Map<String,dynamic>>("/multiapi/c188v_course",data: {"id":widget.courseId}).then((response) {
      setState(() {
        _courseIntro = response.data;
      });
    });
    return null;
  }

  /// 1 分享 2 打卡
  _updateCourse(id,boolShareEnum,boolPunchClockEnum){
    _refresh();
  }
}
